package com.example.user.UserIntegral.service.impl.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.Utility.GeneratedSnowFlake;
import com.example.Utility.publicUtils;
import com.example.entity.OrderMessage;
import com.example.user.UserIntegral.entity.Integral;
import com.example.user.UserIntegral.mapper.IntegarlMapper;
import com.example.user.UserIntegral.service.impl.IntegralService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
public class IntegralImpl extends ServiceImpl<IntegarlMapper, Integral> implements IntegralService {
    @Autowired
    private IntegarlMapper integarlMapper;
    @Autowired
    private IntegralService integralService;

    @Override
    public List<Integral> serviceList(Integral integral) {
        QueryWrapper<Integral> qwr = new QueryWrapper();
        qwr.select().orderByDesc("id");
        qwr.like("openid", integral.getOpenid());
        return integarlMapper.selectList(qwr);
    }

    /**
     * 用户添加积分
     *
     * @param
     * @return
     */
    @Override
    @Transactional
    public Boolean AddIntegral(List<OrderMessage> orderMessages) {
        /*
        判断
         */
        if (orderMessages.isEmpty() && null != orderMessages) {
            throw new RuntimeException("orderMessages is null");
        }
        // 雪花算法初始化
        GeneratedSnowFlake snowFlake = new GeneratedSnowFlake(1, 1, 1);
        // 当前时间
        String currentTime = publicUtils.getTimes("-");
        // 积分集合初始化
        List<Integral> integralList = new ArrayList<>();
        for (OrderMessage os : orderMessages) {
            Integral integral = new Integral(
                    os.getOpenid(), 0, 0, String.valueOf(snowFlake.nextId()).substring(0, 12) + "0001", currentTime
            );
            integralList.add(integral);
        }
        return integralService.saveBatch(integralList);
    }
}
